package com.jf.blogbackened.service.impl;

import com.jf.blogbackened.bean.Category;
import com.jf.blogbackened.bean.PageBean;
import com.jf.blogbackened.bean.Result;
import com.jf.blogbackened.mapper.ArticleMapper;
import com.jf.blogbackened.mapper.CategoryMapper;
import com.jf.blogbackened.service.CategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author David
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public Result getPageData(String name, Integer currentPage, Integer pageSize) {
        Integer total=categoryMapper.getCount(name);
        // 获取总页数(99 10  10页 99/10 9+1=10  100条 10条
        Integer totalPage = total%pageSize==0?total / pageSize : (total / pageSize)+1;
        // 计算偏移量
        Integer offset = (currentPage - 1) * pageSize;
        List<Category> userList=categoryMapper.getPageData(name,offset,pageSize);
        PageBean<Category> pb = new PageBean<>(userList, total, pageSize);
        pb.setCurrentPage(currentPage);
        pb.setPageSize(pageSize);
        pb.setPageCount(totalPage);
         return Result.ok().data(pb);
}

    @Override
    public Result insert(Category category) {
        // 重名校验
        int count =categoryMapper.getCategoryCountByName(category.getName());
        if (count > 0){
            return Result.error().put("message", "该分类已存在");
        }
        category.setCreated(new Date());
        // 插入数据库
        int i = categoryMapper.insert(category);
        // 返回结果
        if(i>0){
            return Result.ok().data(Integer.toString(i));
        }else {
            return Result.error().put("message", "服务器异常");
        }
    }

    @Override
    public Result update(Category category) {
        int i =categoryMapper.update(category);
        if(i>0){
            return Result.ok().data(Integer.toString(i));
        }else {
            return Result.error().put("message", "服务器异常");
        }
    }

    @Override
    public Result getCategoryById(Integer id) {
        Category category =categoryMapper.getCategoryById(id);
        if (category != null) {
            return Result.ok().data(category);
        }else {
            return Result.error().put("message", "参数非法");
        }
    }

    @Override
    public Result delCategoryById(Integer id) {
        // 先删除分类下的文章
        articleMapper.delArticleByCategoryId(id);
        int i =categoryMapper.delCategoryById(id);
        if(i>0){
            return Result.ok().data(Integer.toString(i));
        }else {
            return Result.error().put("message", "服务器异常");
        }
    }

    @Override
    public Result getAllCategory() {
        List<Category > categoryList = categoryMapper.getAllCategory();
        return Result.ok().data(categoryList);

    }
}
